import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/Users.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Goods from '../components/goods/Goods.vue'
import GoodsAdd from '../components/goods/GoodsAdd.vue'
import Params from '../components/goods/Params.vue'
import Categories from '../components/goods/Categories.vue'
import Orders from '../components/orders/Orders.vue'
import Reports from '../components/reports/Reports.vue'
import { Message } from 'element-ui'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/users',
        component: Users
      },
      {
        path: '/rights',
        component: Rights
      },
      {
        path: '/roles',
        component: Roles
      },
      {
        path: '/goods',
        component: Goods
      },
      {
        path: '/goodsadd',
        component: GoodsAdd
      },
      {
        path: '/params',
        component: Params
      },
      {
        path: '/categories',
        component: Categories
      },
      {
        path: '/orders',
        component: Orders
      },
      {
        path: '/reports',
        component: Reports
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 在路由配置生效之前 统一判断token
// to -> 要去的路由配置
// from -> 当前的路由配置
// / -> /login home->login to就是login from就是home路由配置
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // 如果要去的是登录 -> next()
  if (to.path === '/login') return next()
  // 如果要去的不是登录 判断token 如果没有token->login 如果有->next()
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) {
    Message.warning('请先登录')
    return next('/login') // return router.push('/login')
  }
  next()
})

export default router
